package com.wuguitong.serialportdemo;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    public static SerialPortUtil mSerialPortUtil = null;
    private static final int MSG_SHOW_TOAST = 1;
    private Context mContext;
    private Handler handler =  new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_SHOW_TOAST:
                    Toast.makeText(mContext,msg.getData().getString("test"),Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private SerialPortUtil.OnDataReceiveListener lister = new SerialPortUtil.OnDataReceiveListener() {
        @Override
        public void onDataReceive(byte[] buffer, int size) {
            Message msg = new Message();
            msg.what = MSG_SHOW_TOAST;
            Bundle bundle = new Bundle();
            bundle.putString("test",byte2hex(buffer,size));
            msg.setData(bundle);
            handler.sendMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        if(mSerialPortUtil == null) {
            mSerialPortUtil = SerialPortUtil.getInstance();
            mSerialPortUtil.setOnDataReceiveListener(lister);
        }
    }
    public void testNdk(View view) {
        byte[] bytes = {(byte) 0xAA,(byte) 0xBB,(byte) 0xCC};
        mSerialPortUtil.sendBuffer(bytes);
    }
    private String byte2hex(byte[] buffer, int length) {
        String h = "";
        for (int i = 0; i < length; i++) {
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            h = h + " " + temp;
        }
        return h;
    }
}
